<!-- components/enterprise-selector.vue -->
<template>
  <uni-popup ref="popup" type="center" :is-mask-click="false" class="custom-popup">
    <uni-card class="dialog-container">
      <view class="uni-container">
        <uni-easyinput
          v-model="searchText"
          placeholder="请输入企业名称搜索"
          suffixIcon="search"
          @iconClick="handleSearch"
          clearable
          class="search-input"
        ></uni-easyinput>

        <uni-table
          ref="table"
          border
          stripe
          :type="multiple ? 'selection' : ''"
          class="optimized-table"
          @selection-change="handleSelectionChange"
        >
          <uni-tr>
            <uni-th width="40" v-if="type == 'radio'" ></uni-th>
            <uni-th width="120" align="center" class="header-cell">企业名称</uni-th>
            <uni-th width="150" align="center" class="header-cell">经营地址</uni-th>
            <uni-th width="100" align="center" class="header-cell">工单状态</uni-th>
            <uni-th width="120" align="center" class="header-cell">修改时间</uni-th>
          </uni-tr>
          <uni-tr
            v-for="item in tableData"
            :key="item.uniqueId"
            @click.native="handleRowClick(item)"
          >
            <uni-td v-if="type == 'radio'">
              <radio-group @change="radioChange">
                <radio :value="item.id" :checked="item.id === selectId" />
              </radio-group>
            </uni-td>
            <uni-td class="body-cell">{{ item.operatorName }}</uni-td>
            <uni-td class="body-cell">
              <view class="address-text">{{ item.address }}</view>
            </uni-td>
            <uni-td align="center" class="body-cell status-cell">
              <uni-tag
                :text="auditStatusMap[item.auditStatus] || '未完成'"
                :type="item.auditStatus === '1' ? 'success' : 'warning'"
              />
            </uni-td>
            <uni-td align="center" class="body-cell">{{ item.updateDate }}</uni-td>
          </uni-tr>
        </uni-table>

        <view class="pagination-container">
          <uni-pagination
            :page-size="pageSize"
            :current="currentPage"
            :total="total"
            :show-total="true"
            @change="handlePageChange"
          />
        </view>

        <view class="dialog-buttons">
          <button class="cancel-btn" @click="close">取消</button>
          <button class="confirm-btn" @click="confirm">确定</button>
        </view>
      </view>
    </uni-card>
  </uni-popup>
</template>

<script>
import { getMedicalList, listByPage } from '@/api/order'
import { foodProductionList } from '@/api/order'

export default {
  name: 'EnterpriseSelector',
  props: {
    // 是否多选模式
    multiple: {
      type: Boolean,
      default: false
    },
    // 初始选中数据
    initialSelected: {
      type: Array,
      default: () => []
    },
    type: {
      type: String
    },
    tableType: {
      type: String,
      default: '1'
    },
    query: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      searchText: '',
      tableData: [],
      selectedRows: [],
      pageSize: 10,
      total: 0,
      currentPage: 1,
      auditStatusMap: {
        '0': '未完成',
        '1': '已完成'
      },
      selectId: '',
      selectDetail: {}

    }
  },
  watch: {
    initialSelected: {
      immediate: true,
      handler(newVal) {
        this.selectedRows = [...newVal]
      }
    }
  },
  methods: {
    async loadData() {
      try {
        let res;
        let params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          operatorName: this.searchText,
          ...this.query
        }
        if(this.tableType == '1'){
          // res = await getMedicalList(params)
          res = await foodProductionList({
            page: this.currentPage,
            limit: this.pageSize,
            operatorName: this.searchText,
            orderType:'2',
            orderCategory:'17',
            auditStatus:'1'
		 
          })
        }else if(this.tableType == '2'){
          res = await listByPage(params)
        }
        
      //   const res = await foodProductionList({
      //     page: this.currentPage,
      //     limit: this.pageSize,
      //     operatorName: this.searchText,
		  // orderType:'2',
		  // orderCategory:'17',
		  // auditStatus:'1'
		 
      //   })

        if (res.code === 0) {
          this.tableData = res.data.records.map(item => ({
            ...item,
            uniqueId: item.id || Math.random().toString(36).substr(2),
            updateDate: this.formatDate(item.updateDate)
          }))
          this.total = res.data.total
          this.$nextTick(this.setInitialSelection)
        }
      } catch (error) {
        console.error('数据加载失败:', error)
      }
    },

    formatDate(timestamp) {
      if (!timestamp) return '-'
      const date = new Date(timestamp)
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')}`
    },

    handleSearch() {
      this.currentPage = 1
      this.loadData()
    },

    handlePageChange(e) {
      this.currentPage = e.detail.current
      this.loadData()
    },

    handleSelectionChange(e) {
      this.selectedRows = e.detail.value
    },

    handleRowClick(item) {
      if (this.multiple) {
        const index = this.selectedRows.findIndex(i => i.uniqueId === item.uniqueId)
        index === -1 
          ? this.selectedRows.push(item)
          : this.selectedRows.splice(index, 1)
      } else {
        this.selectedRows = [item]
      }
      this.$refs.table.setSelection(this.selectedRows)
    },

    setInitialSelection() {
      const initialIds = this.initialSelected.map(i => i.uniqueId)
      const selectableItems = this.tableData.filter(item => 
        initialIds.includes(item.uniqueId)
      )
      this.$refs.table.setSelection(selectableItems)
    },

    open() {
      this.$refs.popup.open()
      this.loadData()
    },

    close() {
      this.$refs.popup.close()
      this.$emit('close')
    },

    radioChange(e){
      this.selectId = e.detail.value;
      if(!e.detail.value){
        this.selectDetail = {};
      }else {
        this.selectDetail = this.tableData.find(item => item.id === this.selectId)

      } 
      
    },

    confirm() {
      if(this.type == 'radio'){
        this.close();
        this.$emit('confirm', this.selectDetail);
        this.selectId = '';
        this.selectDetail = {};
        return;
      }
      else if (this.selectedRows.length === 0) {
        uni.showToast({ title: '请选择数据', icon: 'none' })
        return
      }
      this.$emit('confirm', this.selectedRows)
      this.close()
    }
  }
}
</script>

<style lang="less" scoped>
.custom-popup {
  width: auto !important;
  min-width: 300px;
  max-width: 80%;
  border-radius: 8px;

  .dialog-container {
    padding: 30px;
    max-height: 80vh;
    overflow-y: auto;
    border-radius: 10px;

    .uni-container {
      width: 100%;

      .search-input {
        margin-bottom: 20px;

        /deep/ .uni-easyinput__content {
          border-radius: 15px;
          padding: 0 15px;
        }
      }

      .optimized-table {
        font-size: 14px;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);

        .header-cell {
          background-color: #f5f7fa !important;
          color: #303133;
          font-weight: 600;
          padding: 12px 8px;
        }

        .body-cell {
          padding: 10px 8px;
          color: #606266;
          line-height: 1.5;

          .address-text {
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }

        .status-cell {
          min-width: 80px;
        }
      }

      .pagination-container {
        margin-top: 20px;
        padding: 12px;
        background: #fff;
        border-radius: 8px;
        display: flex;
        justify-content: flex-end;
      }

      .dialog-buttons {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        margin-top: 20px;

        .cancel-btn {
          background-color: #f0f0f0 !important;
          color: #666 !important;
        }

        .confirm-btn {
          background-color: #2979ff !important;
          color: white !important;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .custom-popup {
    width: 90% !important;

    .dialog-container {
      padding: 15px;

      .optimized-table {
        font-size: 12px;

        .header-cell, .body-cell {
          padding: 6px 4px;
        }
      }

      .pagination-container {
        flex-wrap: wrap;
        justify-content: center;
      }
    }
  }
}
</style>